package cn.siat.auth.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MailTool {
    private static final String REGISTER="注册";
    private static final String FORGET_PASSWORD="忘记密码";
    private static final String BIND_EMAIL="绑定邮箱";
    @Value("${mail.content}")
    private String mailContent;
    @Value("${mail.host}")
    private String hostName;
    @Value("${mail.name}")
    private String fromName;
    @Value("${mail.address}")
    private String fromAddress;
    @Value("${mail.password}")
    private String password;
    @Value("${mail.subject}")
    private String subject;
    @Value("${mail.port}")
    private String port;

    public  boolean send(String emailaddress,Integer message,int type) {
        //发送文案
        String s="";
        if(type==0){
            s=REGISTER;
        }else if(type==1){
            s=FORGET_PASSWORD;
        }else {
            s=BIND_EMAIL;
        }
        String msg = String.format(mailContent,s,message);
        // 准备email
        HtmlEmail email = new HtmlEmail();
        try {
            //填写要发送的email信息
            // 这里是SMTP发送服务器的名字：163的如下："smtp.163.com"
            email.setHostName(hostName);
            // 字符编码集的设置
            email.setCharset("UTF-8");
            // 收件人的邮箱
            email.addTo(emailaddress);
            // 发送人的邮箱
            email.setFrom(fromAddress, fromName);
            // 如果需要认证信息的话，设置认证：用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
            email.setAuthentication(fromAddress, password);
            // 要发送的邮件主题
            email.setSubject(subject);
            // 要发送的信息，可以使用了HtmlEmail，实现邮件内容中使用HTML标签
            email.setMsg(msg);
            //QQ邮箱和企业邮箱端口不一样，企业邮箱用994或465
            email.setSslSmtpPort(port);
            email.setSSLOnConnect(true);
            email.send();
            return true;
        }catch (EmailException e){
            e.printStackTrace();
            return false;
        }
    }
}
